import 'package:dio/dio.dart';
import 'package:enjoy_plus_hm/utils/event_bus.dart';
import 'package:enjoy_plus_hm/utils/toast.dart';
import 'package:enjoy_plus_hm/utils/token.dart';

class NetworkService {
  final _dio = Dio();

  NetworkService() {
    _dio.options.baseUrl = 'https://live-api.itheima.net'; // baseUrl
    _dio.options.connectTimeout = Duration(seconds: 20); // 连接时间
    _dio.options.receiveTimeout = Duration(seconds: 20); // 接收超时时间
    _dio.options.headers = {'Content-Type': 'application/json'}; // 请求头
    _addInterceptors();
  }

  /// get请求
  Future<dynamic> get(String url, {Map<String, dynamic>? params}) async {
    try {
      final res = await _dio.get(url, queryParameters: params);
      return _handelResponse(res);
    } catch (e) {
      return _handleError(e);
    }
  }

  /// post请求
  Future<dynamic> post(String url, {dynamic data}) async {
    try {
      final res = await _dio.post(url, data: data);
      return _handelResponse(res);
    } catch (e) {
      return _handleError(e);
    }
  }

  /// put请求
  Future<dynamic> put(String url, {Map<String, dynamic>? data}) async {
    try {
      final res = await _dio.put(url, data: data);
      _handelResponse(res);
    } catch (e) {
      return _handleError(e);
    }
  }

  /// delete请求
  Future<dynamic> delete(String url, {Map<String, dynamic>? data}) async {
    try {
      final res = await _dio.delete(url, data: data);
      _handelResponse(res);
    } catch (e) {
      return _handleError(e);
    }
  }

  // 成果结果的处理
  _handelResponse(Response response) {
    if (response.statusCode! >= 200 && response.statusCode! < 300) {
      return response.data;
    } else {
      throw Exception('请求失败, 状态码: ${response.statusCode}');
    }
  }

  // 错误结果的处理
  _handleError(error) async {
    if (error is DioException) {
      if (error.type == DioExceptionType.connectionTimeout ||
          error.type == DioExceptionType.receiveTimeout) {
        throw Exception('网络连接超时');
      } else if (error.type == DioExceptionType.badResponse) {
        if (error.response?.statusCode == 401) {
          await TokenManager().removeToken(); // 移除token
          eventBus.fire(LogoutEvent()); // 触发登出事件
          ToastUtil.showInfo('登录过期');
        }
        throw Exception('响应错误，状态码：${error.response?.statusCode}');
      } else {
        throw Exception('网络请求错误：$error');
      }
    } else {
      throw Exception('未知错误：$error');
    }
  }

  // 拦截器
  void _addInterceptors() {
    _dio.interceptors.add(
      InterceptorsWrapper(
        onRequest: (options, handler) async {
          // 请求拦截器：添加公共请求参数、token 等
          final token = TokenManager().getToken() ?? '';
          if (token.isNotEmpty) {
            options.headers['Authorization'] = 'Bearer $token';
          }
          return handler.next(options);
        },
        onResponse: (response, handler) {
          // 响应拦截器：统一处理成功响应
          return handler.next(response);
        },
        onError: (DioException error, handler) {
          // 响应拦截器：统一处理错误响应
          return handler.next(error);
        },
      ),
    );
  }
}

final http = NetworkService();
